import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_boost/boost_navigator.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:flutter_sizefit/flutter_sizefit.dart';
import 'package:flutter_xiecheng/core/extension_business/color_fb.dart';
import 'package:flutter_xiecheng/core/extension/string+extension.dart';
import 'package:flutter_xiecheng/core/extension_business/custom_print.dart';
import 'package:flutter_xiecheng/core/extension_business/empty_page.dart';
import 'package:flutter_xiecheng/core/model/home_model.dart';
import 'package:flutter_xiecheng/core/third_party/refresh_extension.dart';
import 'package:flutter_xiecheng/core/tools/loading_base_view.dart';
import 'package:flutter_xiecheng/core/viewmodel/home_request.dart';
import 'package:flutter_xiecheng/core/widget/home_activity_gridview.dart';
import 'package:flutter_xiecheng/core/widget/home_big_gradview.dart';
import 'package:flutter_xiecheng/core/widget/home_sales_box.dart';
import 'package:flutter_xiecheng/core/widget/home_top_nav_gridview.dart';
import 'package:flutter_xiecheng/page/search/search_bar.dart';


class HomePage extends StatefulWidget {

  // Native传入
  final Map params;

  const HomePage({Key key, this.params}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

  ValueNotifier<bool> withContainer = ValueNotifier(false);
  /// 是否显示loading
  bool _isLoading = true;
  /// 顶部Banner的图片资源
  List<String> _images = [
    'http://pages.ctrip.com/commerce/promote/20180718/yxzy/img/640sygd.jpg',
    'https://dimg04.c-ctrip.com/images/700u0r000000gxvb93E54_810_235_85.jpg',
    'https://dimg04.c-ctrip.com/images/700c10000000pdili7D8B_780_235_57.jpg'
  ];
  // 导航栏的透明度
  double appbarAlpha = 0;
  // 滚动的最大高度，navbar完全显示
  double appbarMaxScrollviewHeight = 100;
  /// 搜索默认文字
  String _default_text = "网红打卡地 景点 酒店 美食";
  /// 首页的model
  HomeModel model;

  List<CommonModel> localNavList = [];
  /// 网格内容
  GridNavModel gridNavModel;

  List<BannerList> bannerList = [];

  EasyRefreshController _controller = EasyRefreshController();

  /// 错误页面
  Widget errorPage;

  // 改变自定义导航栏的透明度
  _onscroll(offset) {
    double alpha = offset / appbarMaxScrollviewHeight;
    if (alpha < 0) {
      alpha = 0;
    } else if (alpha > 1) {
      alpha = 1;
    }
    setState(() {
      appbarAlpha = alpha;
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // 数据请求
    requestData();
  }

  requestData({bool isShowHUD = false}) {
    JKHomeRequest.getHomeData((response) {
      myPrint("请求的结果：$response", StackTrace.current);
      setState(() {
        // 结束刷新
        _controller.finishRefresh();
        _isLoading = false;
        model = response;
        localNavList = response.localNavList;
        gridNavModel = response.gridNav;
        bannerList = response.bannerList;

        errorPage = null;
      });
    }, (errorResponse) {
      _isLoading = false;
      // 结束刷新
      _controller.finishRefresh();
      // 请求失败
      myPrint("请求失败💣💣💣💣💣💣💣 失败的信息：类型：${errorResponse
          .errorType} 错误内容：${errorResponse.errorTypeContent}",
          StackTrace.current);
      if ((errorResponse.errorType == DioErrorType.receiveTimeout ||
          errorResponse.errorType == DioErrorType.connectTimeout ||
          errorResponse.errorType == DioErrorType.other) &&
          model == null) {
        // 显示星球
        errorPage = JKEmptyScreen(
          status: EmptyScreenStatus.network_blocked, refresh: (bool result) {
          myPrint("刷新", StackTrace.current);
          setState(() {
            errorPage = null;
            requestData(isShowHUD: true);
          });
        },);
      } else {
        errorResponse.errorTypeContent.toast();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: JKThemeColor.cN7,
        body: MediaQuery.removePadding(context: context,
            removeTop: true,
            child: JKLoadingWidget(
              isShow: _isLoading,
              text: "加载中...",
              child: NotificationListener(
                onNotification: (ScrollNotification notification ) {
                  if (notification is ScrollStartNotification) {
                    // print("----开始滚动----");
                  } else if (notification is ScrollUpdateNotification) {
                    // 当前滚动的位置和总长度
                    final currentPixel = notification.metrics.pixels;
                    //final totalPixel = notification.metrics.maxScrollExtent;
                    //double progress = currentPixel / totalPixel;
                    if (notification is ScrollUpdateNotification && notification.depth == 0) {
                      // 之寻找一层，不深入监听
                      _onscroll(currentPixel);
                    }
                    // print("正在滚动：${notification.metrics.pixels} - ${notification.metrics.maxScrollExtent}");
                  } else if (notification is ScrollEndNotification) {
                    // print("----结束滚动----");
                  }
                  return true;
                },
                child: Stack(
                  children: model !=null ? [
                    EasyRefresh(
                      onRefresh: () async{
                        myPrint("数据请求🚀🚀🚀🚀🚀🚀🚀🚀", StackTrace.current);
                        requestData();
                      },
                      controller: _controller,
                      enableControlFinishRefresh: true,
                      enableControlFinishLoad: true,
                      topBouncing: true,
                      header: Application.getHeader(),
                      firstRefresh: false,
                      //emptyWidget: _hotListModels.length == 0 ? JKEmptyScreen(status1: EmptyScreenStatus.network_blocked, refresh: (bool result) {
                      //  myPrint("刷新", StackTrace.current);
                      //},) : null,
                      emptyWidget: errorPage == null ? null : errorPage,
                      child: ListView(
                        children: [
                          // 顶部的banner
                          topBaner(),
                          Padding(
                            padding: EdgeInsets.fromLTRB(7, 4, 7, 4),
                            child: HomeTopLocalGridView(models: localNavList, tapCallBack: (tapModel) {
                              BoostNavigator.instance.push(
                                  "webview",
                                  withContainer: withContainer.value,
                                  arguments: {
                                    "hideAppBar": tapModel.hideAppBar,
                                    "icon": tapModel.icon,
                                    "statusBarColor": tapModel.statusBarColor,
                                    "title": tapModel.title,
                                    "url": tapModel.url,
                                  }
                              );
                            },),
                          ),
                          Padding(
                            padding: EdgeInsets.fromLTRB(7, 0, 7, 4),
                            child: HomeBigGradView(gridNavModel: gridNavModel,),
                          ),
                          Padding(
                            padding: EdgeInsets.fromLTRB(7, 0, 7, 4),
                            // 10个活动
                            child: HomeActivityGridView(subNavList: model.subNavList,),
                          ),
                          Padding(
                            padding: EdgeInsets.fromLTRB(7, 0, 7, 4),
                            // 10个活动
                            child: HomeSalesBoxView(salesBoxModel: model.salesBox,),
                          ),
                          Container(
                            height: 0,
                            decoration: BoxDecoration(
                                color: Colors.brown
                            ),
                          )
                        ],
                      ),
                    ),
                    appbarView()
                  ] : [],
                ),
              ),
            )
        )
    );
  }

  /// 顶部banner的设置
  Widget topBaner() {
    return Container(
      height: 150,
      child: Swiper(
        itemCount: bannerList.length,
        autoplay: true,
        itemBuilder: (BuildContext context, int index) {
          return CachedNetworkImage(
            imageUrl: bannerList[index].icon,
            // placeholder: (context, url) => Image.asset(JKAssets.assets_images_placeholder_image,),
            placeholder: _loader,
            errorWidget: _error,
            fit: BoxFit.fill,
          );
        },
        pagination: SwiperPagination(
            builder: DotSwiperPaginationBuilder(
                color: Color(0xff666666),
                activeColor: Colors.white
            )
        ),
        onTap: (int index) {
          print("点击的是：$index");
        },
      ),
    );
  }

  /// 自定义导航栏
  Widget appbarView() {
    return Column(
      children: [
        Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(colors: [Color(0x66000000), Colors.transparent], begin: Alignment.topCenter, end: Alignment.bottomCenter)
          ),
          child: Container(
            height: JKSizeFit.navigationBarHeight,
            padding: EdgeInsets.fromLTRB(0, JKSizeFit.topStatusHeight, 0, 0),
            decoration: BoxDecoration(
              color: Color.fromARGB((appbarAlpha * 255).toInt(), 255, 255, 255)
            ),
            child: SearchBar(
              searchBarType: appbarAlpha > 0.2 ? SearchBarType.homeLight : SearchBarType.home,
              inputBoxClick: _jumpToSearch,
              speakClick: _jumpToSpeak,
              defaultText: _default_text,
              leftButtonClick: () {},
            ),
          ),
        ),
        Container(
          height: appbarAlpha > 0.2 ? 0.5 : 0,
          decoration: BoxDecoration(
            boxShadow: [BoxShadow(color: Colors.black12, blurRadius: 0.5)]
          ),
        )
      ],
    );
  }

  // TODO: 暂时废弃
  Widget oldAppbarView() {
    return  Opacity(
      opacity: appbarAlpha,
      child: Container(
        height: JKSizeFit.navigationBarHeight,
        decoration: BoxDecoration(
            color: Colors.white
        ),
        child: Center(
          child: Padding(
            padding: EdgeInsets.only(top: JKSizeFit.topStatusHeight),
            child: Text("首页", style: TextStyle(
                fontSize: 18,
                color: Colors.black
            ),),
          ),
        ),
      ),
    );
  }

  Widget _loader(BuildContext context, String url) {
    return const Center(
      child: CircularProgressIndicator(
        color: Colors.brown,
      ),
    );
  }

  Widget _error(BuildContext context, String url, dynamic error) {
    return const Center(child: Icon(Icons.error));
  }

  /// 跳转搜索界面
  _jumpToSearch() {
    setState(() {
      BoostNavigator.instance.push(
          "search_screen",
          withContainer: withContainer.value,
          arguments: {
            "hideLeft": false,
            "keyword": '12',
            "hint": '搜索呀'
          }
      );
    });
  }

  /// 跳转语音界面
  _jumpToSpeak() {
    BoostNavigator.instance.push(
        "speak_page",
        withContainer: withContainer.value
    );
  }
}

